/**
 * @description 用户体验增强工具
 * @author 张一依有把越女剑
 * @date 2025-04-16
 */

// 加载状态管理
class LoadingManager {
	constructor() {
		this.loadingStates = new Map()
		this.globalLoading = false
	}
	
	show(key = 'global', options = {}) {
		const config = {
			title: '加载中...',
			mask: true,
			...options
		}
		
		this.loadingStates.set(key, true)
		
		if (key === 'global') {
			this.globalLoading = true
			uni.showLoading(config)
		}
	}
	
	hide(key = 'global') {
		this.loadingStates.set(key, false)
		
		if (key === 'global') {
			this.globalLoading = false
			uni.hideLoading()
		}
	}
	
	isLoading(key = 'global') {
		return this.loadingStates.get(key) || false
	}
	
	hideAll() {
		this.loadingStates.clear()
		this.globalLoading = false
		uni.hideLoading()
	}
}

export const loadingManager = new LoadingManager()

// 消息提示增强
export class MessageManager {
	constructor() {
		this.messageQueue = []
		this.isShowing = false
	}
	
	success(message, duration = 2000) {
		this.show({
			title: message,
			icon: 'success',
			duration
		})
	}
	
	error(message, duration = 3000) {
		this.show({
			title: message,
			icon: 'error',
			duration
		})
	}
	
	warning(message, duration = 2500) {
		this.show({
			title: message,
			icon: 'none',
			duration,
			image: '/static/icons/warning.png'
		})
	}
	
	info(message, duration = 2000) {
		this.show({
			title: message,
			icon: 'none',
			duration
		})
	}
	
	show(options) {
		this.messageQueue.push(options)
		this.processQueue()
	}
	
	async processQueue() {
		if (this.isShowing || this.messageQueue.length === 0) {
			return
		}
		
		this.isShowing = true
		const message = this.messageQueue.shift()
		
		uni.showToast(message)
		
		setTimeout(() => {
			this.isShowing = false
			this.processQueue()
		}, message.duration || 2000)
	}
	
	clear() {
		this.messageQueue = []
		uni.hideToast()
		this.isShowing = false
	}
}

export const messageManager = new MessageManager()

// 确认对话框增强
export function showConfirm(options) {
	const defaultOptions = {
		title: '提示',
		content: '确定要执行此操作吗？',
		confirmText: '确定',
		cancelText: '取消',
		confirmColor: '#1890ff'
	}
	
	const config = { ...defaultOptions, ...options }
	
	return new Promise((resolve) => {
		uni.showModal({
			...config,
			success: (res) => {
				resolve(res.confirm)
			},
			fail: () => {
				resolve(false)
			}
		})
	})
}

// 操作反馈
export class FeedbackManager {
	// 触觉反馈
	vibrate(type = 'light') {
		const types = {
			light: { type: 'light' },
			medium: { type: 'medium' },
			heavy: { type: 'heavy' }
		}
		
		if (uni.vibrateShort) {
			uni.vibrateShort(types[type] || types.light)
		}
	}
	
	// 声音反馈
	playSound(type = 'click') {
		// 这里可以播放不同类型的音效
		// uni.createInnerAudioContext() 可以用来播放音频
	}
	
	// 视觉反馈 - 按钮点击效果
	buttonFeedback(element) {
		if (!element) return
		
		element.style.transform = 'scale(0.95)'
		element.style.transition = 'transform 0.1s'
		
		setTimeout(() => {
			element.style.transform = 'scale(1)'
		}, 100)
	}
}

export const feedbackManager = new FeedbackManager()

// 页面切换动画
export class PageTransition {
	static slideIn(direction = 'right') {
		return {
			animationType: 'slide-in-' + direction,
			animationDuration: 300
		}
	}
	
	static fadeIn() {
		return {
			animationType: 'fade-in',
			animationDuration: 300
		}
	}
	
	static zoomIn() {
		return {
			animationType: 'zoom-in',
			animationDuration: 300
		}
	}
	
	static navigate(url, transition = 'slideIn') {
		const animations = {
			slideIn: this.slideIn(),
			fadeIn: this.fadeIn(),
			zoomIn: this.zoomIn()
		}
		
		uni.navigateTo({
			url,
			...animations[transition]
		})
	}
}

// 表单验证增强
export class FormValidator {
	constructor() {
		this.rules = {}
		this.errors = {}
	}
	
	addRule(field, rule) {
		if (!this.rules[field]) {
			this.rules[field] = []
		}
		this.rules[field].push(rule)
	}
	
	validate(data) {
		this.errors = {}
		let isValid = true
		
		Object.keys(this.rules).forEach(field => {
			const value = data[field]
			const fieldRules = this.rules[field]
			
			fieldRules.forEach(rule => {
				if (!rule.validator(value)) {
					if (!this.errors[field]) {
						this.errors[field] = []
					}
					this.errors[field].push(rule.message)
					isValid = false
				}
			})
		})
		
		return {
			isValid,
			errors: this.errors
		}
	}
	
	getFirstError() {
		const fields = Object.keys(this.errors)
		if (fields.length > 0) {
			return this.errors[fields[0]][0]
		}
		return null
	}
}

// 常用验证规则
export const validationRules = {
	required: (message = '此字段为必填项') => ({
		validator: (value) => value !== null && value !== undefined && value !== '',
		message
	}),
	
	minLength: (min, message) => ({
		validator: (value) => !value || value.length >= min,
		message: message || `最少需要${min}个字符`
	}),
	
	maxLength: (max, message) => ({
		validator: (value) => !value || value.length <= max,
		message: message || `最多允许${max}个字符`
	}),
	
	email: (message = '请输入有效的邮箱地址') => ({
		validator: (value) => !value || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
		message
	}),
	
	phone: (message = '请输入有效的手机号码') => ({
		validator: (value) => !value || /^1[3-9]\d{9}$/.test(value),
		message
	}),
	
	number: (message = '请输入有效的数字') => ({
		validator: (value) => !value || !isNaN(Number(value)),
		message
	}),
	
	range: (min, max, message) => ({
		validator: (value) => {
			if (!value) return true
			const num = Number(value)
			return num >= min && num <= max
		},
		message: message || `请输入${min}到${max}之间的数字`
	})
}

// 用户引导
export class UserGuide {
	constructor() {
		this.steps = []
		this.currentStep = 0
		this.isActive = false
	}
	
	addStep(step) {
		this.steps.push({
			target: step.target,
			title: step.title,
			content: step.content,
			position: step.position || 'bottom'
		})
	}
	
	start() {
		if (this.steps.length === 0) return
		
		this.isActive = true
		this.currentStep = 0
		this.showStep()
	}
	
	showStep() {
		const step = this.steps[this.currentStep]
		if (!step) return
		
		// 这里可以实现具体的引导UI显示逻辑
		// 比如高亮目标元素，显示提示框等
		console.log('Showing guide step:', step)
	}
	
	next() {
		if (this.currentStep < this.steps.length - 1) {
			this.currentStep++
			this.showStep()
		} else {
			this.finish()
		}
	}
	
	prev() {
		if (this.currentStep > 0) {
			this.currentStep--
			this.showStep()
		}
	}
	
	finish() {
		this.isActive = false
		this.currentStep = 0
		// 隐藏引导UI
	}
	
	skip() {
		this.finish()
	}
}

// 无障碍访问支持（适配小程序环境）
export class AccessibilityHelper {
	static announceForScreenReader(message) {
		// 在小程序环境中，使用其他方式提供无障碍支持
		if (typeof uni !== 'undefined') {
			// 小程序环境下的无障碍提示
			console.log('Screen reader announcement:', message)
			return
		}

		// 浏览器环境下的屏幕阅读器支持
		if (typeof document !== 'undefined') {
			const announcement = document.createElement('div')
			announcement.setAttribute('aria-live', 'polite')
			announcement.setAttribute('aria-atomic', 'true')
			announcement.style.position = 'absolute'
			announcement.style.left = '-10000px'
			announcement.textContent = message

			document.body.appendChild(announcement)

			setTimeout(() => {
				document.body.removeChild(announcement)
			}, 1000)
		}
	}

	static setFocusToElement(selector) {
		if (typeof document !== 'undefined') {
			const element = document.querySelector(selector)
			if (element) {
				element.focus()
			}
		}
	}
	
	static addKeyboardNavigation(container) {
		const focusableElements = container.querySelectorAll(
			'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
		)
		
		focusableElements.forEach((element, index) => {
			element.addEventListener('keydown', (e) => {
				if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
					e.preventDefault()
					const nextIndex = (index + 1) % focusableElements.length
					focusableElements[nextIndex].focus()
				} else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
					e.preventDefault()
					const prevIndex = (index - 1 + focusableElements.length) % focusableElements.length
					focusableElements[prevIndex].focus()
				}
			})
		})
	}
}
